package com.yx.shop.dao.impl;

import com.yx.shop.dao.AddressDao;
import com.yx.shop.entitly.Address;
import com.yx.shop.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Classname AddressDaoImpl
 * @Description TODO:
 * @Date 2021/05/08 20:56
 * @Created by yx
 */
public class AddressDaoImpl implements AddressDao {
    private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public int insert(Address address) {
        String sql = "INSERT INTO address(uid,aname,aphone,adetail,astate) VALUES(?,?,?,?,?);";
        Object[] args = {address.getUid(),address.getAname(),address.getAphone(),address.getAdetail(),address.getAstate()};
        try {
           return queryRunner.update(sql,args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Address> getAddList(int uid) {
        try {
            String sql = "SELECT * FROM address WHERE uid = ? ORDER BY astate DESC;";
            return queryRunner.query(sql,new BeanListHandler<>(Address.class),uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer deleteAddByAid(Integer aid) {
        try {
            String sql = "delete from address where aid = ?;";
            return queryRunner.update(sql,aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int setNotDefault(int uid) {
        try {
            return queryRunner.update("update address set astate = 0 where uid = ?;",uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int setDefault(Integer aid) {
        try {
            return queryRunner.update("update address set astate = 1 where aid = ?;",aid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateAdd(Address address) {
        try {
            String sql = "update address set aname=?,aphone=?,adetail=? where aid=? and uid=?";
            Object[] args = {address.getAname(), address.getAphone(), address.getAdetail(), address.getAid(),address.getUid()};
            return queryRunner.update(sql, args);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
